package org.csu.mypetstore.api.controller.front;

import com.zhenzi.sms.ZhenziSmsClient;
import org.csu.mypetstore.api.entity.Orders;
import org.csu.mypetstore.api.service.OrderService;
import org.springframework.util.DigestUtils;
import org.csu.mypetstore.api.common.CommonResponse;
import org.csu.mypetstore.api.common.ResponseCode;
import org.csu.mypetstore.api.entity.Account;
import org.csu.mypetstore.api.service.AccountService;
import org.csu.mypetstore.api.vo.AccountVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/account/")
public class AccountController {

    @Autowired
    private AccountService accountService;
    @Autowired
    private OrderService orderService;

    //获取用户信息
    @GetMapping("information")
    @ResponseBody
    public CommonResponse<AccountVO> getAccount(HttpSession session){
        AccountVO accountVO = (AccountVO)session.getAttribute("login_account");
        if(accountVO != null){
            CommonResponse<AccountVO> response = accountService.getAccount(accountVO.getUsername());
            session.setAttribute("login_account",response.getData());
            session.setAttribute("username",response.getData().getUsername());
            System.out.println(session.getAttribute("username"));
            return response;
        }else{
            return CommonResponse.createForError("用户未登录，不能获取用户信息");
        }
    }

    //用户请求登录
    @PostMapping("login")
    @ResponseBody
    public CommonResponse<AccountVO> login(@RequestParam String username,@RequestParam String password, HttpSession session){
        CommonResponse<AccountVO> response = accountService.getAccount(username,password);
        if(response.isSuccess()){
            session.setAttribute("login_account",response.getData());
        }
        return  response;
    }

    //用户登录检测
    @PostMapping("get_login_account_info")
    @ResponseBody
    public CommonResponse<AccountVO> getLoginAccountInfo(HttpSession session){
        AccountVO loginAccount = (AccountVO)session.getAttribute("login_account");
        if(loginAccount != null){
            return CommonResponse.createForSuccess(loginAccount);
        }
        return CommonResponse.createForError("用户未登录，不能获取用户信息");
    }

    //用户登出
    @PostMapping("logout")
    @ResponseBody
    public CommonResponse logoff(HttpSession session) {
        AccountVO loginAccount = (AccountVO)session.getAttribute("login_account");
        if(loginAccount != null){
            session.removeAttribute("login_account");
            return CommonResponse.createForSuccessMessage("成功退出登录");
        }
        return CommonResponse.createForError("用户未登录，不用退出登录状态");
    }

    //用户注册
    @PostMapping("register")
    @ResponseBody
    public CommonResponse<AccountVO> register(AccountVO accountVO,HttpSession session) {
        CommonResponse<String> isExist = accountService.usernameExist(accountVO.getUsername());
        if (isExist.getMsg().equals("用户名不存在")) {
            CommonResponse<AccountVO> response = accountService.insertAccount(accountVO);
            AccountVO account = accountService.getAccount(accountVO.getUsername()).getData();
            session.setAttribute("login_account", account);
            return response;
        } else if (isExist.getMsg().equals("用户名已存在")){
            return CommonResponse.createForError("用户名已存在");
        } else {
            return CommonResponse.createForError("服务器异常");
        }
    }

    //用户更新信息
    @PostMapping("update")
    @ResponseBody
    public CommonResponse<AccountVO> update(AccountVO accountVO, HttpSession session) {
        // 更新用户信息
        AccountVO account = accountService.getAccount(accountVO.getUsername()).getData();
        accountVO.setStatus(account.getStatus());
        accountVO.setBannerName(account.getBannerName());

        if(accountVO.getPassword().equals("")){
            accountVO.setPassword(accountService.getPassword(account.getUsername()).getData());
        }

        CommonResponse<AccountVO> response = accountService.updateAccount(accountVO);
        session.setAttribute("login_account", response.getData());
        return response;
    }

    // 判断用户名是否已存在
    @PostMapping("user_exist")
    @ResponseBody
    public CommonResponse<String> userExist(@RequestParam("username") String username) {
        return  accountService.usernameExist(username);
    }

    //发送短信验证码
    @PostMapping("sendCode")
    @ResponseBody
    public CommonResponse<String> sendCode(@RequestParam("memPhone") String memPhone, HttpServletRequest request) throws Exception{
        HttpSession session = request.getSession();
        String apiUrl = "https://sms_developer.zhenzikj.com";
        String appId = "111123";
        String appSecret = "cdd7ee86-e79f-4c79-a835-1f6fd2bafde7";
        ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("number", memPhone);
        params.put("templateId", "8519");
        int randomNum = (int)(Math.random()*(9999-1000+1))+1000;
        String strRandom = Integer.toString(randomNum);
        session.setAttribute("strRandom",strRandom);
        String[] templateParams = new String[1];
        templateParams[0] = strRandom;
        params.put("templateParams", templateParams);
        String result = client.send(params);
        System.out.println(result);
        if(result.equals("0")){
            CommonResponse<String> response = CommonResponse.createForSuccessMessage("发送失败");
            return response;
        }else{
            CommonResponse<String> response = CommonResponse.createForSuccess(strRandom);
            return response;
        }
    }

    //获取所有orders
    @GetMapping("orders")
    @ResponseBody
    public CommonResponse<List<Orders>> getOrderListbyUsername(HttpSession session){
        String username=(String) session.getAttribute("username");
        if (username != null) {
            System.out.println("account is OK OK OK OK OK OK!!!!!!!!!!!!!!!!!!!!!!!!!!");
            CommonResponse<List<Orders>> response = orderService.getOrderListbyUsername(username);
            return response;
        } else {
            System.out.println("account is null!!!!!!!!!!!!!!!!!!!!!!!!!!"+new Date());
            return CommonResponse.createForError("用户未登录，不能获取用户订单");
        }
    }
}
